import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Leetcode2013 {
    public static void main(String[] args) {
        DetectSquares detectSquares = new DetectSquares();
        detectSquares.add(new int[]{419,351});
        detectSquares.add(new int[]{798,351});
        detectSquares.add(new int[]{798,730});
        System.out.println(detectSquares.count(new int[]{419, 730}));
        detectSquares.add(new int[]{998,1});
        detectSquares.add(new int[]{0,999});
        detectSquares.add(new int[]{998,999});
        System.out.println(detectSquares.count(new int[]{0, 1}));
    }

    static class DetectSquares {
        Map<Pair, Integer> map;

        public DetectSquares() {
            map = new HashMap<>();
        }

        public void add(int[] point) {
            Pair pair = new Pair(point[0], point[1]);
            if (map.containsKey(pair)) {
                map.put(pair, map.get(pair) + 1);
            } else {
                map.put(pair, 1);
            }
        }

        public int count(int[] point) {
            int count = 0;
            int x = point[0];
            int y = point[1];
            for (Map.Entry<Pair, Integer> entry : map.entrySet()) {
                if (entry.getKey().y != y) {
                    continue;
                }

                int length = Math.abs(entry.getKey().x - x);

                Pair pair1 = new Pair(entry.getKey().x, entry.getKey().y + length);
                Pair pair2 = new Pair(x, y + length);
                if (map.containsKey(pair1) && map.containsKey(pair2)) {
                    count = count + (map.get(pair1) * map.get(pair2) * entry.getValue());
                }

                pair1 = new Pair(entry.getKey().x, entry.getKey().y - length);
                pair2 = new Pair(x, y - length);
                if (map.containsKey(pair1) && map.containsKey(pair2)) {
                    count = count + (map.get(pair1) * map.get(pair2) * entry.getValue());
                }
            }

            return count;
        }


        static class Pair {
            int x;
            int y;

            public Pair(int x, int y) {
                this.x = x;
                this.y = y;
            }

            @Override
            public boolean equals(Object o) {
                if (this == o) {
                    return true;
                }
                if (o == null || getClass() != o.getClass()) {
                    return false;
                }
                Pair pair = (Pair) o;
                return x == pair.x && y == pair.y;
            }

            @Override
            public int hashCode() {
                return Objects.hash(x, y);
            }
        }
    }

}
